#include <opencv2/opencv.hpp>
#include <iostream>
#include <vector>

using namespace cv;
using namespace std;

int main()
{
    Mat img=imread("/home/lwj/opencv.21/0.jpg");
    if (img.empty())
    {
        cout<<"no"<<endl;
        return -1;
    }
    imshow("原图",img);
    Mat gray,binary;
    cvtColor(img,gray,COLOR_BGR2GRAY);//灰度
    GaussianBlur(gray,gray,Size(13,13),4,4);//高斯
    threshold(gray,binary,170,255,THRESH_BINARY | THRESH_OTSU);//自适应二值化
    
    vector<vector<Point>>contours;//轮廓坐标点
    vector<Vec4i>hierarchy;//轮廓结构变量
    findContours(binary,contours,hierarchy,RETR_TREE,CHAIN_APPROX_SIMPLE,Point());//统计轮廓
//输出轮廓
    for(int i=0;i<contours.size();i++)
    {
        drawContours(img,contours,i,Scalar(0,0,255),2,8);
    }
//输出轮廓结构描述
    for(int j=0;j<hierarchy.size();j++)
    {
        cout<<hierarchy[j]<<endl;
    }
    //输出轮廓面积
    for(int t=0;t<contours.size();t++)
    {
        double area=contourArea(contours[t]);
        cout<<"第"<<t<<"轮廓面积="<<area<<endl;
    }
    //输出轮廓长度
    for(int k=0;k<contours.size();k++)
    {
        double length=arcLength(contours[k],true);
        cout<<"第"<<k<<"个轮廓长度"<<length<<endl;
    }


    imshow("轮廓",img);
    waitKey(0);
    return 0;
}